package cn.sieis.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.sieis.pojo.Project;
import cn.sieis.pojo.Source;
import cn.sieis.service.project.ProjectService;
import cn.sieis.service.source.SourceService;
import cn.sieis.tools.DateUtil;
import cn.sieis.tools.FastDFSClient;

@Controller

public class SignFrontController {
	@Autowired
	private SourceService sourceService;

	@Autowired
	private ProjectService projectService;

	@RequestMapping(value = "/front/sign.html", method = RequestMethod.GET)
	public String sign(@ModelAttribute("project") Project project) {
		return "front/sign";
	}

	@RequestMapping(value = "/front/savesign.html", method = RequestMethod.POST)
	public String signSave(HttpSession session, HttpServletRequest request) {
		try {
			String proName = request.getParameter("proName");
			String details = request.getParameter("details");
			String creationDate = request.getParameter("creationDate");
			String proStatus = request.getParameter("proStatus");
			Project project = new Project();
			if (StringUtils.isNoneBlank(creationDate)) {
				Date date = new SimpleDateFormat("yyyy-MM-dd").parse(creationDate);
				project.setCreationDate(date);
			}
			project.setDetails(details);
			project.setProName(proName);
			project.setProStatus(Integer.valueOf(proStatus));
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> files = multipartRequest.getFiles("file");
			Optional<MultipartFile> optional = files.stream().findFirst();
			if (optional.isPresent()) {
				MultipartFile file = optional.get();
				Source source = new Source();
				String filename = file.getOriginalFilename();
				source.setFilename(filename);
				// 上传文件的关键两行代码
				String str = FastDFSClient.uploadFile(file);
				String filepath = FastDFSClient.getResAccessUrl(str);
				source.setPubtime(DateUtil.getNowTime());
				source.setFilepath(filepath);
				project.setFilePath(filepath);
				sourceService.addSource(source);
			}

			if (projectService.sign(project)) {
				System.out.println(1);
				return "front/index";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "front/sign";
	}
}
